package com.osfw.system.service.dict.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.osfw.framework.constants.Constants;
import com.osfw.framework.constants.UserConstants;
import com.osfw.framework.core.domain.Ztree;
import com.osfw.framework.exception.ServiceException;
import com.osfw.framework.utils.CacheUtils;
import com.osfw.framework.utils.StringUtils;
import com.osfw.framework.utils.text.Convert;
import com.osfw.system.entity.dict.SysDictData;
import com.osfw.system.entity.dict.SysDictType;
import com.osfw.system.mapper.dict.SysDictDataMapper;
import com.osfw.system.mapper.dict.SysDictTypeMapper;
import com.osfw.system.service.dict.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 字典 业务层处理
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService {

    @Autowired
    private SysDictDataMapper dictDataMapper;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init() {
        loadingDictCache();
    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeList(SysDictType dictType) {
        LambdaQueryWrapper<SysDictType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(dictType.getDictName()), SysDictType::getDictName, dictType.getDictName());
        queryWrapper.eq(StringUtils.isNotEmpty(dictType.getStatus()), SysDictType::getStatus, dictType.getStatus());
        queryWrapper.like(StringUtils.isNotEmpty(dictType.getDictType()), SysDictType::getDictType, dictType.getDictType());
        queryWrapper.ge(dictType.getBeginTime() != null, SysDictType::getCreateTime, dictType.getBeginTime());
        queryWrapper.le(dictType.getEndTime() != null, SysDictType::getCreateTime, dictType.getEndTime());
        return list(queryWrapper);
    }

    /**
     * 根据所有字典类型
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeAll() {
        return list();
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {
        List<SysDictData> dictDatas = StringUtils.cast(CacheUtils.get(getCacheName(), getCacheKey(dictType)));
        if (StringUtils.isNotEmpty(dictDatas)) {
            return dictDatas;
        }
        LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictData::getStatus, '0').eq(SysDictData::getDictType, dictType).orderByAsc(SysDictData::getDictSort);
        dictDatas = dictDataMapper.selectList(queryWrapper);
        if (StringUtils.isNotEmpty(dictDatas)) {
            CacheUtils.put(getCacheName(), getCacheKey(dictType), dictDatas);
            return dictDatas;
        }
        return null;
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeById(Long dictId) {
        return getById(dictId);
    }

    /**
     * 根据字典类型查询信息
     *
     * @param dictType 字典类型
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeByType(String dictType) {
        LambdaQueryWrapper<SysDictType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictType::getDictType, dictType);
        return getOne(queryWrapper);
    }

    /**
     * 批量删除字典类型
     *
     * @param ids 需要删除的数据
     */
    @Override
    public void deleteDictTypeByIds(String ids) {
        List<SysDictType> dictTypes = listByIds(Arrays.asList(Convert.toLongArray(ids)));
        for (SysDictType dictType : dictTypes) {
            LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysDictData::getDictType, dictType.getDictType());
            if (dictDataMapper.selectCount(queryWrapper) > 0) {
                ServiceException.throw500(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            removeById(dictType.getDictId());
            CacheUtils.remove(getCacheName(), getCacheKey(dictType.getDictType()));
        }
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache() {
        LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictData::getStatus, "0");
        Map<String, List<SysDictData>> dictDataMap = dictDataMapper.selectList(queryWrapper).stream().collect(Collectors.groupingBy(SysDictData::getDictType));
        for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet()) {
            CacheUtils.put(getCacheName(), getCacheKey(entry.getKey()), entry.getValue().stream().sorted(Comparator.comparing(SysDictData::getDictSort)).collect(Collectors.toList()));
        }
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache() {
        CacheUtils.removeAll(getCacheName());
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    public boolean insertDictType(SysDictType dict) {
        boolean save = save(dict);
        if (save) {
            CacheUtils.put(getCacheName(), getCacheKey(dict.getDictType()), null);
        }
        return save;
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean updateDictType(SysDictType dict) {
        SysDictType oldDict = getById(dict.getDictId());
        SysDictData dictData = new SysDictData();
        dictData.setDictType(dict.getDictType());
        dictDataMapper.update(dictData, new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getDictType, oldDict.getDictType()));
        boolean update = updateById(dict);
        if (update) {
            LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysDictData::getStatus, "0");
            queryWrapper.eq(SysDictData::getDictType, dict.getDictType());
            queryWrapper.orderByAsc(SysDictData::getDictSort);
            List<SysDictData> dictDatas = dictDataMapper.selectList(queryWrapper);
            CacheUtils.put(getCacheName(), getCacheKey(dict.getDictType()), dictDatas);
        }
        return update;
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public String checkDictTypeUnique(SysDictType dict) {
        Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
        LambdaQueryWrapper<SysDictType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictType::getDictType, dict.getDictType());
        List<SysDictType> list = list(queryWrapper);
        if (list != null && !list.isEmpty()) {
            if (StringUtils.isNotNull(list.get(0)) && list.get(0).getDictId().longValue() != dictId.longValue()) {
                return Constants.NOT_UNIQUE;
            }
        }
        return Constants.UNIQUE;
    }

    /**
     * 查询字典类型树
     *
     * @param dictType 字典类型
     * @return 所有字典类型
     */
    @Override
    public List<Ztree> selectDictTree(SysDictType dictType) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<SysDictType> dictList = selectDictTypeList(dictType);
        for (SysDictType dict : dictList) {
            if (UserConstants.DICT_NORMAL.equals(dict.getStatus())) {
                Ztree ztree = new Ztree();
                ztree.setId(dict.getDictId());
                ztree.setName(transDictName(dict));
                ztree.setTitle(dict.getDictType());
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    public String transDictName(SysDictType dictType) {
        StringBuffer sb = new StringBuffer();
        sb.append("(" + dictType.getDictName() + ")");
        sb.append("&nbsp;&nbsp;&nbsp;" + dictType.getDictType());
        return sb.toString();
    }

    /**
     * 获取cache name
     *
     * @return 缓存名
     */
    private String getCacheName() {
        return Constants.SYS_DICT_CACHE;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return Constants.SYS_DICT_KEY + configKey;
    }

}
